package com.brother.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.brother.database.DataBase;
import com.brother.model.EmailSetting;
import com.brother.util.CommonProperties;

import org.apache.commons.mail.*;

public class EmailSettingService {

	
public 	EmailSetting getEmailSetting(String userid){
	EmailSetting set = null;
	String sql = "select * from emailSetting where userid="+userid;
	
	try {
		ResultSet rs = DataBase.query(sql);
		if(rs.next()){
			set = new EmailSetting();
			set.setEmailSettingId(rs.getInt("emailSettingId"));
			set.setUserId(rs.getInt("userid"));
			set.setMailHost(rs.getString("mailhost"));
			set.setMailUsername(rs.getString("mailUsername"));
			set.setMailPassword(rs.getString("mailPassword"));
			set.setPort(rs.getString("port"));
			set.setMailEnabled(rs.getBoolean("mailEnabled"));
			set.setSslEnabled(rs.getBoolean("SslEnabled"));
		}
	} catch (SQLException e) {
		Logger.getLogger(this.getClass()).error(e);
	}
	DataBase.closeConnection();
	return set;
}
public int setEmail(EmailSetting set){
	String sql = "";
	if(set.getEmailSettingId() == 0){ // 添加一个设置
		sql = "insert into EmailSetting(userid,mailhost,mailUsername,mailPassword,port,mailEnabled,createdate) " +
			"values("+set.getUserId()+",'"+set.getMailHost()+"','"+set.getMailUsername()+"'," +
			"'"+set.getMailPassword()+"','"+set.getPort()+"',"+set.isMailEnabled()+",now())";	
	}else { // update 一个设置
		sql = "update EmailSetting" +
		" set userid="+set.getUserId()+",mailhost='"+set.getMailHost()
		+"',mailUsername='"+set.getMailUsername()+"',mailPassword=" +
		"'"+set.getMailPassword()+"',port='"+set.getPort()+
		"',mailEnabled="+set.isMailEnabled()+",sslEnabled="+set.isSslEnabled()+" where emailsettingid="+set.getEmailSettingId();		
	}
	
	Logger.getLogger(this.getClass()).debug(sql);
	
	if(sql.length() < 10)
		return 0;
	int r = DataBase.update(sql);
	DataBase.closeConnection();
	return r;
}

public String sendMail(EmailSetting set, String content,String subject){
	String info = "";
	try {
		HtmlEmail  mail = new HtmlEmail ();
		mail.setAuthentication(set.getMailUsername(), set.getMailPassword());
		mail.setHostName(set.getMailHost());// smtp.126.com
		//mail.isSSL()
		mail.setSSL(set.isSslEnabled());
		mail.addTo(set.getMailUsername());
		mail.setFrom(set.getMailUsername());
		mail.setSubject(subject);
		mail.setContent(content+CommonProperties.getEmailFooter(), "text/html;charset=utf-8");
		mail.setSmtpPort(Integer.parseInt(set.getPort()));
		//mail.setMsg(context); // 用这个会中文乱码
		mail.send();
	} catch (EmailException e) {
		Logger.getLogger(this.getClass()).error(e);
		info = e.getMessage();
	}
	return info;
}

	
}
